﻿using System;
using System.Net;

namespace SvnDeploy.Service.Impl
{
    internal class VirtualDirectoryUpdaterImpl : IVirtualDirectoryUpdater
    {
        public VirtualDirectoryUpdaterImpl(IFileSystem fileSystem, ISvnAdapter svnAdapter, IBackupProvider backupProvider)
        {
            BackupProvider = backupProvider;
            FileSystem = fileSystem;
            SvnAdapter = svnAdapter;            
        }

        public IBackupProvider BackupProvider { get; private set; }

        public IFileSystem FileSystem { get; private set; }

        public long Revision { get; private set; }

        public ISvnAdapter SvnAdapter { get; private set; }

        public bool WasUpdated { get; private set; }

        public virtual void CheckOutOrUpdate(string name, string svnPath, string localPath)
        {
            VerifyDirectoryExists(localPath);
            if (FileSystem.IsDirectoryEmpty(localPath))
            {
                SvnAdapter.CheckOut(new Uri(svnPath), localPath);
                SetRevisionValues();
                BackupProvider.Backup(name, localPath);
            }
            else
            {
                SvnAdapter.Update(localPath);
                SetRevisionValues();
                if (WasUpdated)
                {
                    BackupProvider.Backup(name, localPath);
                }
            }
        }

        public virtual void Dispose()
        {
            if (SvnAdapter != null)
            {
                SvnAdapter.Dispose();
            }
        }

        public virtual void SetAuthentication(ICredentials credentials)
        {
            SvnAdapter.SetAuthentication(credentials);
        }

        private void SetRevisionValues()
        {
            WasUpdated = SvnAdapter.WasUpdated;
            Revision = SvnAdapter.Revision;
        }

        private void VerifyDirectoryExists(string virtualDirectory)
        {
            if (!FileSystem.DoesDirectoryExist(virtualDirectory))
            {
                FileSystem.CreateDirectory(virtualDirectory);
            }
        }
    }
}
